#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys, signal, commands, hashlib, os, platform, re, tempfile, time, os, os.path, string, subprocess, codecs, locale, multiprocessing, datetime

import socket


def kill_ngx_process_by():
    """

    :return:
    """
    ipv4 = get_host_ipv4()

    cmd = "ps aux | grep nginx | grep 'nginx.conf' | awk '{ print $2 }'"
    status, output = commands.getstatusoutput(cmd)
    if output is not None and len(output) > 0:
        i = 0
        arr = output.split('\n')
        for pid in arr:
            i += 1
            os.system("echo 'pid={}---------------------------------------------------------index={}'".format(pid, i))
            os.system("echo 'nginx is already running with (pid= %s), i will kill it soon--->%s'" % (pid, ipv4))
            cmd = 'kill %s' % (pid)
            os.system(cmd)
            os.system("echo 'nginx which pid is %s be killed--->%s'" % (pid, ipv4))
            os.system("echo ''")
    else:
        os.system("echo ''")
        os.system("echo 'there is no nginx running--->%s'" % (ipv4))
        os.system("echo ''")

def get_host_ipv4():
    """
    :return: ipv4
    """
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ipv4 = s.getsockname()[0]
    except Exception, e:
        ipv4 = '0.0.0.0'
    finally:
        s.close()

    return ipv4

def main():
    kill_ngx_process_by()

if __name__ == '__main__':
    sys.exit(main())
